<template>
  <div class="live-player-wrapper" v-show="playerShow">
    <div class="live-title" v-if="title">
<!--      <i v-if="needPlayIcon" class="fas fa-play-circle icon"></i>-->
      <span class="text">{{title}}</span>
<!--      <span class="btn-wrapper" v-if="needChange">-->
<!--        <span @click="$emit('changeMap', selfPos)"><i class="fas fa-external-link-alt"></i></span>-->
<!--        <span @click="$emit('changeCenter')"><i class="fas fa-th-large"></i></span>-->
<!--      </span>-->
      <slot name="zoom"></slot>
    </div>
    <div class="live-player" :class="[!isMobile? 'pc': '', tele]">
      <teleport :to="moveTarget">
        <video
            muted
            autoplay
            :id="videoId"
            :src="videoUrl"
            class="live-video"
            v-show="videoShow"
            :poster="posterImg"
            :controls="showControls"
        >
        </video>
        <div class="rest-frame" v-if="restStatus && showRest">
          <svg-icon icon-class="rest"></svg-icon>
          <span>休息中...</span>
        </div>
      </teleport>
    </div>
  </div>
</template>

<script>
import flvjs from "flv.js"
import { AliRTS } from "aliyun-rts-sdk"
import { isSupportAliRts } from "@/utils/alirts"
import { defineComponent, ref, onMounted, onUnmounted } from 'vue'
import { isMobileDevice } from '@/utils/util'
import SrsPlayer from '@/utils/srsplayer'

export default defineComponent ({
  name: "LivePlayer",
  props: {
    tele: String,
    title: String,
    videoId: String,
    videoUrl: String,
    mapWrapper: String,
    needChange: {
      type: Boolean,
      default: true
    },
    needPlayIcon: {
      type: Boolean,
      default: true
    },
    posterImg: {
      type: String,
    },
    showRest: {
      type: Boolean,
      default: true
    },
    showControls: {
      type: Boolean,
      default: true
    }
  },
  emits: ['closePlayer', 'changeMap', 'changeCenter'],
  setup(props, ctx) {

    let useSrs = ref(false)
    const srsPlayer = new SrsPlayer()
    let [aliRts, flvPlayer, videoEle] = [ AliRTS.createClient(), null, null ]

    const selfPos = `.${props.tele}`
    const moveTarget = ref('#app')
    const videoShow = ref(false)
    const restStatus = ref(true)
    const playerShow = ref(true)
    const isMobile = ref(isMobileDevice())
    let lastWebrtcUrl = null

    const createPlayer = async (pullUrl) => {
      restStatus.value = false
      videoEle = document.getElementById(props.videoId)
      useSrs.value = pullUrl.webrtc != null
      if (useSrs.value) {
        if (pullUrl.webrtc == lastWebrtcUrl) return;
        lastWebrtcUrl = pullUrl.webrtc;

        await srsPlayer.play(pullUrl.webrtc)
        videoEle.srcObject = srsPlayer.stream
      }
      else if (await isSupportAliRts(aliRts) && pullUrl.artc) {
        aliRts.subscribe(pullUrl.artc).then((remoteStream) => {
          remoteStream.play(videoEle)
        }).catch((err) => {
          console.log(`${pullUrl.artc}-播放失败`)
        })
      }
      else if (flvjs.isSupported()) {
        const mediaData = {type: 'flv', url: pullUrl.flv}
        flvPlayer = flvjs.createPlayer(mediaData)
        flvPlayer.attachMediaElement(videoEle)
        flvPlayer.on(flvjs.Events.SCRIPTDATA_ARRIVED, () => {
          flvPlayer.load()
          flvPlayer.play()
        })
      }
      else if (isMobile.value) {
        videoEle.src = pullUrl.hls
      }
    }

    const closePlayer = async () => {
      if (useSrs.value) {
        srsPlayer.close()
        lastWebrtcUrl = null
      }
      else if (await isSupportAliRts(aliRts)) {
        aliRts.unsubscribe()
      }
      else if (flvjs.isSupported()) {
        flvPlayer.unload()
        flvPlayer.detachMediaElement()
        flvPlayer.destroy()
      }
      else if (isMobile.value) {
        videoEle.src = ''
      }

      restStatus.value = true
    }


    onMounted(() => {
      moveTarget.value = selfPos
      videoShow.value = true
      window.addEventListener('resize', () => {
        isMobile.value = isMobileDevice()
      })
    })

    onUnmounted(() => {
      closePlayer()
    })


    return {
      isMobile,
      selfPos,
      useSrs,
      videoShow,
      moveTarget,
      createPlayer,
      closePlayer,
      restStatus,
      playerShow,
    }
  }
})
</script>

<style lang="scss" src="./index.scss"></style>
